﻿using System;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Xml;
using MouseExtender.Logic.Common;
using MouseExtender.Logic.Entities;

namespace MouseExtender.Logic.Managers
{
    public class SettingsManager
    {
        private static UserSettings _settings;
        private static object _settingsLock = new object();

        public string SettingFileName
        {
            get;
            private set;
        }

        public static UserSettings CurrentSettings
        {
            get
            {
                if (_settings == null)
                    lock (_settingsLock)
                    {
                        if (_settings == null)
                            _settings = new SettingsManager().LoadSettings();
                    }
                return _settings;
            }
        }

        public SettingsManager()
        {
            string assemblyName = Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName;
            SettingFileName = Path.Combine(Path.GetDirectoryName(assemblyName), Constants.SettingsFileName);
        }

        public SettingsManager(string settingsFileName)
        {
            SettingFileName = settingsFileName;
        }

        public UserSettings LoadSettings()
        {
            UserSettings settings = null;
            if (!File.Exists(SettingFileName))
            {
                settings = new UserSettings();
            }
            else
            {
                using (FileStream stream = new FileStream(SettingFileName, FileMode.Open))
                {
                    XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas());
                    DataContractSerializer serializer = new DataContractSerializer(typeof(UserSettings));
                    settings = (UserSettings)serializer.ReadObject(reader, true);
                    reader.Close();
                    stream.Close();
                }
            }

            settings.SetParametersDefaultsIfValueNotSpecified();

            return settings;
        }

        public void SaveSettings(UserSettings settings)
        {
            using (FileStream stream = new FileStream(SettingFileName, FileMode.Create, FileAccess.Write))
            {
                DataContractSerializer serializer = new DataContractSerializer(typeof(UserSettings));
                try
                {
                    serializer.WriteObject(stream, settings);
                }
                catch (Exception ex)
                {
                    Logger.HandleCriticalError(ex);
                }
                finally
                {
                    stream.Close();
                }
            }
        }

    }
}
